package com.seguriapp.complaints.gwt.server;

import net.customware.gwt.dispatch.server.ExecutionContext;
import net.customware.gwt.dispatch.shared.DispatchException;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.restlet.resource.ClientResource;

import com.seguriapp.common.config.GlobalConfigLoader;
import com.seguriapp.common.gwt.server.AbstractSeguriAppHandler;
import com.seguriapp.complaints.gwt.shared.ChangeComplaintVisibilityAction;
import com.seguriapp.complaints.gwt.shared.ChangeComplaintVisibilityResult;

public class ChangeComplaintVisibilityHandler extends AbstractSeguriAppHandler<ChangeComplaintVisibilityAction, ChangeComplaintVisibilityResult> {

  private static final Logger LOGGER = Logger.getLogger(ChangeComplaintVisibilityHandler.class);

  public Class<ChangeComplaintVisibilityAction> getActionType() {
    return ChangeComplaintVisibilityAction.class;
  }

  public ChangeComplaintVisibilityResult execute(final ChangeComplaintVisibilityAction action, final ExecutionContext context)
      throws DispatchException {

    final ChangeComplaintVisibilityResult result = new ChangeComplaintVisibilityResult();
    try {
      final String url = GlobalConfigLoader.getInstance().getGlobalConfig().getBackEndUrl()
          .concat(GlobalConfigLoader.getInstance().getGlobalConfig().getChangeComplaintVisibility());
      final ClientResource resource = new ClientResource(url);
      final String complaintListStr = resource.post(convertDataToJsonString(action)).getText();
      LOGGER.info("Data received : \n" + complaintListStr);
      result.setSuccess(getResponseFromString(complaintListStr));
      result.setMapVisibility(action.isMapVisibility());
    } catch (Exception e) {
      LOGGER.error("Error al cambiar la visibilidad de la denuncia", e);
    }
    return result;
  }

  private String convertDataToJsonString(final ChangeComplaintVisibilityAction action) {
    final JSONObject obj = new JSONObject();
    try {
      obj.put("complaintId", action.getComplaintId());
      obj.put("mapVisibility", action.isMapVisibility());

    } catch (JSONException e) {
      LOGGER.error("Error al convertir parametros de denuncia a json", e);
    }
    LOGGER.info("Sending Data : \n" + obj.toString());
    return obj.toString();
  }

  private boolean getResponseFromString(final String complaintListStr) {
    return complaintListStr != null && complaintListStr.equals("true");
  }

}
